//
//  CommonMethod.m
//  BSNL_Market
//
//  Created by ayi on 16/04/2018.
//  Copyright © 2018 ayi. All rights reserved.
//

#import "CommonMethod.h"

#import <YYCategories/UIView+YYAdd.h>
#import <YYCategories/NSDate+YYAdd.h>
#import <CoreText/CoreText.h>
#import "NSString+Util.h"
#import <CommonCrypto/CommonDigest.h>
@implementation CommonMethod

+ (UIColor *) colorFromHexString:(NSString *)hexString{
    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    {
        if([cleanString length] == 3) {
            cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
                           [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                           [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                           [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
        }
    }
    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }
    
    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
    
    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;
    float alpha = ((baseValue >> 0) & 0xFF)/255.0f;
    
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

+ (NSString *)stringFormTimeStamp:(double )timeStampString formatString:(NSString *)formatString{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatString];
    NSDate *nadateTimeFromTimesp = [NSDate dateWithTimeIntervalSince1970:timeStampString];
    NSString *stringFromTimespStr =[formatter stringFromDate:nadateTimeFromTimesp];
    return stringFromTimespStr;
}

+ (NSString *)uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}


//计算lab的高度
+(CGSize)labWidthFromStr:(NSString *)content andFont:(UIFont *)font andWidth:(CGFloat )width{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGSize stringSize = [content boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return stringSize;
}

+(CGSize)labWidthFromAttributedString:(nonnull NSAttributedString *)content andWidth:(CGFloat )width{
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)content);
    return CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(framesetter, content, CGSizeMake(width, MAXFLOAT), 1000);
}

static inline CGSize CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(CTFramesetterRef framesetter, NSAttributedString *attributedString, CGSize size, NSUInteger numberOfLines) {
    CFRange rangeToSize = CFRangeMake(0, (CFIndex)[attributedString length]);
    CGSize constraints = CGSizeMake(size.width, 10000);
    
    if (numberOfLines == 1) {
        // If there is one line, the size that fits is the full width of the line
        constraints = CGSizeMake(10000, 10000);
    } else if (numberOfLines > 0) {
        // If the line count of the label more than 1, limit the range to size to the number of lines that have been set
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, CGRectMake(0.0f, 0.0f, constraints.width, 10000));
        CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
        CFArrayRef lines = CTFrameGetLines(frame);
        
        if (CFArrayGetCount(lines) > 0) {
            NSInteger lastVisibleLineIndex = MIN((CFIndex)numberOfLines, CFArrayGetCount(lines)) - 1;
            CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex);
            
            CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine);
            rangeToSize = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length);
        }
        
        CFRelease(frame);
        CGPathRelease(path);
    }
    CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, rangeToSize, NULL, constraints, NULL);
    CFRelease(framesetter);
    return CGSizeMake(ceilf(suggestedSize.width), ceilf(suggestedSize.height));
}

//lab 的公共创建方式
+ (UILabel *)customLabInitWith:(CGFloat )fontSize andTextColor:(UIColor *)color andAlign:(NSTextAlignment )textAlign{
    UILabel *lab = [[UILabel alloc]init];
    lab.font = FONT_SIZE(fontSize);;
    lab.textColor = color;
    lab.textAlignment = textAlign;
    lab.layer.masksToBounds = YES;
    return lab;
}
+ (UILabel *)customLabInitWith:(CGFloat )fontSize andTextColor:(UIColor *)color andAlign:(NSTextAlignment )textAlign withBgColor:(UIColor *)bgcolor{
    UILabel *lab = [self customLabInitWith:fontSize andTextColor:color andAlign:textAlign];
    lab.backgroundColor = bgcolor?bgcolor:UIColor.whiteColor;
    return lab;
}

//UITextField 的公共创建方式;
+ (UITextField *)customTextFieldInitWith:(CGFloat )fontSize andTextColor:(UIColor *)color andAlign:(NSTextAlignment )textAlign andPlaceholder:(NSString *)placeholder{
    UITextField *textf = [[UITextField alloc]init];
    textf.font = FONT_SIZE(fontSize);
    textf.textColor = color;
    textf.textAlignment = textAlign;
    textf.placeholder = placeholder;
    textf.clearButtonMode = UITextFieldViewModeWhileEditing;
    return textf;
}
// 根据宽高计算压缩后的分辨率，宽高同时不超过设置的最大值
+ (CGSize)conversionSizeWithSize:(CGSize)size maxWidth:(float )maxWidth maxHeight:(float )maxHeight {
    float scaleWidth = 1;
    float scaleHeight = 1;
    if (size.width > maxWidth) {
        scaleWidth = (float)maxWidth / (float)size.width;
    }
    if (size.height > maxHeight) {
        scaleHeight = (float)maxHeight / (float)size.height;
    }
    
    float scale = MIN(scaleHeight, scaleWidth);
    CGSize conversionSize = CGSizeMake(size.width * scale, size.height * scale);
    
    return conversionSize;
}
//为控件添加虚线
+ (void)addLimaginaryLineWithView:(UIView *)view andWidth:(CGFloat )width andColor:(UIColor *)color andLineDashPattern:(NSArray *)patAry{
    CAShapeLayer *border = [CAShapeLayer layer];
    border.strokeColor = color.CGColor;
    border.fillColor = [UIColor clearColor].CGColor;
    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
    border.frame = view.bounds;
    border.lineWidth = width;
    border.lineDashPattern = patAry;//@[@4, @2]
    [view.layer addSublayer:border];
}

//根据颜色创建图片
+ (UIImage *) createImageWithColor:(UIColor *) color WithFrame:(CGRect )frame
{
    CGRect rect=frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *)createImageCircleWithColor:(UIColor *) color WithFrame:(CGRect )frame{
    UIImage *img = [self createImageWithColor:color WithFrame:frame];
    
    UIGraphicsBeginImageContextWithOptions(frame.size,NO,0);
    UIBezierPath*path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0,0,frame.size.width,frame.size.height)];
    [path addClip];
    [img drawAtPoint:CGPointZero];
    
    UIImage*image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)createImageCircleWithImage:(UIImage *)img{
    UIGraphicsBeginImageContextWithOptions(img.size,NO,0);
    UIBezierPath*path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0,0,img.size.width,img.size.height)];
    [path addClip];
    [img drawAtPoint:CGPointZero];
    
    UIImage*image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/**
 给指点图片添加自定义背景 形成新的图片

 @param rect 背景大小
 @param placeImage 填充图片
 @param bgColor 填充背景颜色
 @param NoTranslucence 是否半透明 YES为不透明
 @return 新的图片
 */
+ (UIImage *) createImgWithBgViewFrame:(CGRect)rect withDefaultImage:(UIImage *)placeImage withBgColor:(UIColor *)bgColor withNoTranslucence:(BOOL)NoTranslucence
{
    UIView *bgView = [[UIView alloc]initWithFrame:rect];
    if (bgColor != nil)
        bgView.backgroundColor = bgColor;
    else
        bgView.backgroundColor = [CommonMethod colorFromHexString:@"#EAEAEA"];
    UIImage *img;
    if (placeImage) {
        img = placeImage;
    } else {
        img = [UIImage getDefaultImage];
    }
    CGFloat width = rect.size.width > img.size.width?img.size.width:rect.size.width;
    CGFloat height = rect.size.height > img.size.height?img.size.height:rect.size.height;
    CGFloat finilyWidth = width>height?height:width;
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, finilyWidth, finilyWidth)];
    imgView.centerX = bgView.centerX;
    imgView.centerY = bgView.centerY;
    imgView.image = img;
    [bgView addSubview:imgView];
    CGSize size = rect.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(size, NoTranslucence, [UIScreen mainScreen].scale);
    [bgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


//颜色渐变
+ (CAGradientLayer *)layerColorGradualchange:(UIView *)view fromColor:(UIColor *)fromHexColor toColor:(UIColor *)toHexColor{
    //    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)fromHexColor.CGColor,(__bridge id)toHexColor.CGColor];
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0, 0.5);
    gradientLayer.endPoint = CGPointMake(1, 0.5);
    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];
    
    return gradientLayer;
}



//Core Graphics
+ (UIImage *)coreGraphicsColorGradualchange:(CGSize )size fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor{
    //创建CGContextRef
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //创建CGMutablePathRef
    CGMutablePathRef path = CGPathCreateMutable();
    
    //绘制Path
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
    CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect));
    CGPathCloseSubpath(path);

    //绘制渐变
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    
    NSArray *colors = @[(__bridge id) fromColor.CGColor, (__bridge id) toColor.CGColor];
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    
    
    CGRect pathRect = CGPathGetBoundingBox(path);
    //具体方向可根据需求修改
//    CGPoint startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMidY(pathRect));
//    CGPoint endPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMidY(pathRect));
    
    CGPoint startPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMinY(pathRect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMaxY(pathRect));
    
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
    
    //注意释放CGMutablePathRef
    CGPathRelease(path);
    
    //从Context中获取图像，并显示在界面上
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

//创建二维码
+ (UIImage *)createQrcodeWithUrl:(NSString *)url withSize:(CGFloat) size{
    if (url == nil) {
        return nil;
    }
    //创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    //将NSString格式转化成NSData格式
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    [filter setValue:data forKeyPath:@"inputMessage"];
    //获取二维码过滤器生成的二维码
    CIImage *image = [filter outputImage];
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [self compoundImg:[UIImage imageWithCGImage:scaledImage] andImg2:IMG(@"img_login_logo")];
}
//合成图片
+ (UIImage *)compoundImg:(UIImage *)img1 andImg2:(UIImage *)img2 {

    UIGraphicsBeginImageContextWithOptions(img1.size,NO,2);
    [img1 drawInRect:CGRectMake(0, 0, img1.size.width, img1.size.height)];
    [img2 drawInRect:CGRectMake((img1.size.width*5/6)/2, (img1.size.width*5/6)/2, img1.size.width/6, img1.size.width/6)];
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImg;
}



+ (CGSize)getWidthWithStr:(NSString *)content andFont:(UIFont *)font andWidth:(CGFloat )width{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGSize stringSize = [content boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return stringSize;
}


+(NSString *)getTimeStrFromSeconds:(NSInteger )seconds{
    NSString *format_time = @"";
    if (seconds > 3600*24) {
        format_time = [format_time stringByAppendingString:[NSString stringWithFormat:@"%02ld天",(long)seconds/(3600*24)]];
        seconds -= (seconds/(3600*24))*(3600*24);
    }
    if (seconds > 3600) {
        format_time = [format_time stringByAppendingString:[NSString stringWithFormat:@"%02ld时",(long)seconds/3600]];
        seconds -= (seconds/3600)*3600;
    }
    if (seconds > 60) {
        format_time = [format_time stringByAppendingString:[NSString stringWithFormat:@"%02ld分",(long)seconds/60]];
        seconds -= (seconds/60)*60;
    }
    format_time = [format_time stringByAppendingString:[NSString stringWithFormat:@"%02ld秒",(long)seconds]];
    return format_time;
}

+(NSString *)getTimeStrFromTime:(NSDate *)date{
    NSString *format_time = @"";
    if (date == nil) {
        return format_time;
    }
    NSTimeInterval timeint = [date timeIntervalSince1970];
    NSTimeInterval nowTimeInt = [[NSDate date]timeIntervalSince1970];
    int seconds = nowTimeInt - timeint;

    if (seconds <= 1) {
        format_time = @"刚刚";
    }else if (seconds <= 60) {
        format_time = [NSString stringWithFormat:@"%d秒前",seconds];
    }else if (seconds <= 3600) {
        format_time = [NSString stringWithFormat:@"%d分钟前",seconds/60];
    }else if ([date isToday]) {
        format_time = [CommonMethod stringFormTimeStamp:timeint formatString:@"HH:mm"];
    }else if ([date isYesterday]) {
        format_time = [CommonMethod stringFormTimeStamp:timeint formatString:@"昨天 HH:mm"];
    }else{
        format_time = [CommonMethod stringFormTimeStamp:timeint formatString:@"yyyy-MM-dd"];
    }
    return format_time;
}

+(NSString *)getTimeStrFromTime2:(NSDate *)date{
    NSString *format_time = @"";
    if (date == nil) {
        return format_time;
    }
    NSTimeInterval timeint = [date timeIntervalSince1970];
    NSTimeInterval nowTimeInt = [[NSDate date]timeIntervalSince1970];
    int seconds = nowTimeInt - timeint;
    
    if (seconds <= 1) {
        format_time = @"刚刚";
    }else if (seconds <= 60) {
        format_time = [NSString stringWithFormat:@"%d秒前",seconds];
    }else if (seconds <= 3600) {
        format_time = [NSString stringWithFormat:@"%d分钟前",seconds/60];
    }else if ([date isToday]) {
        format_time = [NSString stringWithFormat:@"%d小时前",seconds/3600];
    }else{
        format_time = [CommonMethod stringFormTimeStamp:timeint formatString:@"yyyy-MM-dd"];
    }
    return format_time;
}





+ (void)shakeAnimationForView:(UIView *) view
{
    // 获取到当前的View
    CALayer *viewLayer = view.layer;
    // 获取当前View的位置
    CGPoint position = viewLayer.position;
    // 移动的两个终点位置
    CGPoint x = CGPointMake(position.x + 10, position.y);
    CGPoint y = CGPointMake(position.x - 10, position.y);
    // 设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    // 设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    // 设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    // 设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    // 设置自动反转
    [animation setAutoreverses:YES];
    // 设置时间
    [animation setDuration:.06];
    // 置次数
    [animation setRepeatCount:3];
    // 添加上动画
    [viewLayer addAnimation:animation forKey:nil];
    
}


+ (void )getAPPCacheSize:(void(^)(NSString *size))callback{
    [[SDImageCache sharedImageCache]calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
        long long sizeLength = totalSize;
        if (sizeLength < 1024) {// 小于1k
            if(callback)
                callback([NSString stringWithFormat:@"%ldB",(long)sizeLength]);
        }else if (sizeLength < 1024 * 1024){// 小于1m
            CGFloat aFloat = sizeLength/1024;
            if(callback)
               callback([NSString stringWithFormat:@"%.0fK",aFloat]);
        }else if (sizeLength < 1024 * 1024 * 1024){// 小于1G
            CGFloat aFloat = sizeLength/(1024 * 1024);
            if(callback)
                callback([NSString stringWithFormat:@"%.1fM",aFloat]);
        }else{
            CGFloat aFloat = sizeLength/(1024*1024*1024);
            if(callback)
                callback([NSString stringWithFormat:@"%.1fG",aFloat]);
        }
    }];
}

+ (void)deleteCache:(void(^)(BOOL isok))callback{
    [[SDImageCache sharedImageCache]clearMemory];
    [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
        if (callback) {
            callback(YES);
        }
    }];
}



+ (BOOL )showViewWithDateTimeFromCurrent{
    NSDate *date = [NSDate date];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:8];
    [inputFormatter setTimeZone:GTMzone];
    NSDate* inputDate = [inputFormatter dateFromString:@"2018-12-23"];
    NSTimeInterval interval = [date timeIntervalSinceDate:inputDate];
    if (interval < 0) {
        return NO;
    } else {
        return YES;
    }
}


+ (NSString *)createMD5Key:(NSString *)md5Paraname
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSString *paraname = [NSString stringWithFormat:@"%@%@%@",md5Paraname,currentTimeString,@",car,"];
    return [[self alloc] md5:paraname];
    
}


+ (NSString *)createShaKey:(NSString *)shaParaname
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSString *paraname = [NSString stringWithFormat:@"%@%@%@",[[self alloc] sha1:shaParaname],currentTimeString,@",car,"];
    return [[self alloc] md5:paraname];

}


- (NSString *) md5:(NSString *) str
{
    
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];

    
}


- (NSString*) sha1:(NSString *)str
{
    const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithBytes:cstr length:str.length];
    //使用对应的CC_SHA1,CC_SHA256,CC_SHA384,CC_SHA512的长度分别是20,32,48,64
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    //使用对应的CC_SHA256,CC_SHA384,CC_SHA512
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}


+ (void)saveUser:(UserRes *)user
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:data forKey:@"user"];
    
}

+ (UserRes *)getUser
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    //取出
    NSData *data = [user objectForKey:@"user"];
    UserRes *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return model;
    
}

+ (BOOL)isBlankString:(NSString *)string
{

    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    
    return NO;
    
}

+ (void)saveUserName:(NSString *)mobile
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:mobile];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:data forKey:@"mobile"];
    
}
+ (NSString *)getUserName
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    //取出
    NSData *data = [user objectForKey:@"mobile"];
    NSString *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return model;
    
}

@end
